package com.micro.train.controller;

import com.micro.train.entity.Train;
import com.micro.train.service.TrainService;
import com.micro.train.service.TrainSeatService;
import com.micro.train.dto.TrainInventoryDTO;
import com.micro.train.dto.TrainResponseDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 火车信息控制器
 */
@Tag(name = "火车信息管理", description = "火车信息相关接口")
@RestController
@RequestMapping("/api/trains")
public class TrainController {
    
    @Autowired
    private TrainService trainService;
    
    @Autowired
    private TrainSeatService trainSeatService;
    
    @Operation(summary = "添加列车信息")
    @PostMapping
    public ResponseEntity<Train> addTrain(@RequestBody Train train) {
        Train savedTrain = trainService.addTrain(train);
        return ResponseEntity.ok(savedTrain);
    }
    
    @Operation(summary = "更新列车信息")
    @PutMapping("/{trainId}")
    public ResponseEntity<Train> updateTrain(@PathVariable Long trainId, @RequestBody Train train) {
        Train updatedTrain = trainService.updateTrain(trainId, train);
        return ResponseEntity.ok(updatedTrain);
    }
    
    @Operation(summary = "删除列车信息")
    @DeleteMapping("/{trainId}")
    public ResponseEntity<Void> deleteTrain(@PathVariable Long trainId) {
        trainService.deleteTrain(trainId);
        return ResponseEntity.noContent().build();
    }
    
    @Operation(summary = "获取所有列车信息")
    @GetMapping
    public ResponseEntity<List<Train>> getAllTrains() {
        List<Train> trains = trainService.getAllTrains();
        return ResponseEntity.ok(trains);
    }
    
    @Operation(summary = "根据ID获取列车信息")
    @GetMapping("/{trainId}")
    public ResponseEntity<Map<String, Object>> getTrainById(@PathVariable Long trainId) {
        Train train = trainService.getTrainById(trainId);
        if (train == null) {
            return ResponseEntity.notFound().build();
        }
        
        Map<String, Object> trainMap = new HashMap<>();
        trainMap.put("列车ID", train.getTrainId());
        trainMap.put("车次", train.getTrainNumber());
        trainMap.put("始发站ID", train.getDepartureStationId());
        trainMap.put("终点站ID", train.getTerminalStationId());
        trainMap.put("始发时间", train.getDepartureTime());
        trainMap.put("终到时间", train.getArrivalTime());
        
        return ResponseEntity.ok(trainMap);
    }
    
    @Operation(summary = "根据车次查询列车信息")
    @GetMapping("/number/{trainNumber}")
    public ResponseEntity<Map<String, Object>> getTrainByNumber(@PathVariable String trainNumber) {
        System.out.println("DEBUG - 查询车次: " + trainNumber);
        
        // 临时解决方案：获取所有列车然后过滤
        List<Train> allTrains = trainService.getAllTrains();
        System.out.println("DEBUG - 所有列车数量: " + allTrains.size());
        
        Train train = allTrains.stream()
            .filter(t -> trainNumber.equals(t.getTrainNumber()))
            .findFirst()
            .orElse(null);
        
        System.out.println("DEBUG - 查询结果: " + train);
        
        if (train == null) {
            return ResponseEntity.notFound().build();
        }
        
        System.out.println("DEBUG - 列车ID: " + train.getTrainId());
        System.out.println("DEBUG - 车次: " + train.getTrainNumber());
        System.out.println("DEBUG - 始发站ID: " + train.getDepartureStationId());
        System.out.println("DEBUG - 终点站ID: " + train.getTerminalStationId());
        System.out.println("DEBUG - 始发时间: " + train.getDepartureTime());
        System.out.println("DEBUG - 终到时间: " + train.getArrivalTime());
        
        Map<String, Object> trainMap = new HashMap<>();
        trainMap.put("列车ID", train.getTrainId());
        trainMap.put("车次", train.getTrainNumber());
        trainMap.put("始发站ID", train.getDepartureStationId());
        trainMap.put("终点站ID", train.getTerminalStationId());
        trainMap.put("始发时间", train.getDepartureTime());
        trainMap.put("终到时间", train.getArrivalTime());
        
        return ResponseEntity.ok(trainMap);
    }
    
    @Operation(summary = "根据列车类型查询")
    @GetMapping("/type/{trainType}")
    public ResponseEntity<List<Train>> getTrainsByType(@PathVariable String trainType) {
        List<Train> trains = trainService.getTrainsByType(trainType);
        return ResponseEntity.ok(trains);
    }
    
    @Operation(summary = "根据始发站ID查询")
    @GetMapping("/departure/{stationId}")
    public ResponseEntity<List<Train>> getTrainsByDepartureStation(@PathVariable Long stationId) {
        List<Train> trains = trainService.getTrainsByDepartureStation(stationId);
        return ResponseEntity.ok(trains);
    }
    
    @Operation(summary = "根据终点站ID查询")
    @GetMapping("/terminal/{stationId}")
    public ResponseEntity<List<Train>> getTrainsByTerminalStation(@PathVariable Long stationId) {
        List<Train> trains = trainService.getTrainsByTerminalStation(stationId);
        return ResponseEntity.ok(trains);
    }
    
    @Operation(summary = "根据状态查询")
    @GetMapping("/status/{status}")
    public ResponseEntity<List<Train>> getTrainsByStatus(@PathVariable Integer status) {
        List<Train> trains = trainService.getTrainsByStatus(status);
        return ResponseEntity.ok(trains);
    }
    
    @Operation(summary = "根据始发站和终点站查询")
    @GetMapping("/route")
    public ResponseEntity<List<Train>> getTrainsByRoute(
            @RequestParam Long departureStationId,
            @RequestParam Long terminalStationId) {
        List<Train> trains = trainService.getTrainsByRoute(departureStationId, terminalStationId);
        return ResponseEntity.ok(trains);
    }
    
    @Operation(summary = "检查车次是否存在")
    @GetMapping("/exists/{trainNumber}")
    public ResponseEntity<Boolean> existsByTrainNumber(@PathVariable String trainNumber) {
        boolean exists = trainService.existsByTrainNumber(trainNumber);
        return ResponseEntity.ok(exists);
    }
    
    @Operation(summary = "获取列车库存信息")
    @GetMapping("/{trainId}/inventory")
    public ResponseEntity<TrainInventoryDTO> getTrainInventory(@PathVariable Long trainId) {
        try {
            // 默认查询今天的库存
            LocalDate today = LocalDate.now();
            TrainInventoryDTO inventory = trainSeatService.getTrainInventory(trainId, today);
            return ResponseEntity.ok(inventory);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    @Operation(summary = "获取指定日期的列车库存信息")
    @GetMapping("/{trainId}/inventory/date")
    public ResponseEntity<TrainInventoryDTO> getTrainInventoryByDate(
            @PathVariable Long trainId,
            @RequestParam String travelDate) {
        try {
            LocalDate date = LocalDate.parse(travelDate);
            TrainInventoryDTO inventory = trainSeatService.getTrainInventory(trainId, date);
            return ResponseEntity.ok(inventory);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    @Operation(summary = "获取可用座位数量")
    @GetMapping("/{trainId}/seats/available")
    public ResponseEntity<Integer> getAvailableSeatCount(
            @PathVariable Long trainId,
            @RequestParam Integer seatType,
            @RequestParam(required = false) String travelDate) {
        try {
            LocalDate date = travelDate != null ? LocalDate.parse(travelDate) : LocalDate.now();
            Integer count = trainSeatService.getAvailableSeatCount(trainId, seatType, date);
            return ResponseEntity.ok(count);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
}
